package github.sf.fw.tools.db.model;

import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Data
public class TableWithPage {
    private int page;
    private int size;
    private int count;
    private List<ColumnStructureInfo> structures;

    private List<Map<String, String>> records;

    public static TableWithPage of(TableDataWithPage tableDataWithPage) {
        TableWithPage tableWithPage = new TableWithPage();
        tableWithPage.setPage(tableDataWithPage.getPage());
        tableWithPage.setCount(tableDataWithPage.getCount());
        tableWithPage.setSize(tableDataWithPage.getSize());
        tableWithPage.fromResultRows(tableDataWithPage.getRecords());
        return tableWithPage;
    }

    public void fromResultRows(List<ResultRow> resultRows) {
        if (records == null) {
            records = new ArrayList<>();
        }
        if (structures == null) {
            structures = new ArrayList<>();
        }
        if (CollectionUtils.isEmpty(resultRows)) {
            return;
        }
        boolean first = true;
        for (ResultRow resultRow : resultRows) {
            int colIndex = 0;
            Map<String, String> rowMap = new LinkedHashMap<>();
            for (ResultData resultData : resultRow) {
//                Map<String, Object> colObj = new IdentityHashMap<>();
                if (first) {
                    resultData.setColumnIndex(colIndex);
                    ColumnStructureInfo columnStructureInfo = fromResultData(resultData);
                    structures.add(columnStructureInfo);
                }
                String columnName = resultData.getColumnName().intern();
                String value = String.valueOf(resultData.getColumnValue());
//                colObj.put(columnName, value);
//                colObj.put("columnValueAsString", value);
//                colObj.put(columnName + "Index", colIndex);
                rowMap.put(columnName, value);
                colIndex++;
            }
            records.add(rowMap);
            first = false;
        }
    }

    private ColumnStructureInfo fromResultData(ResultData columnInfo) {
        ColumnStructureInfo columnStructureInfo = new ColumnStructureInfo();
        columnStructureInfo.setColumnName(columnInfo.getColumnName());
        columnStructureInfo.setColumnIndex(columnInfo.getColumnIndex());
        columnStructureInfo.setColumnType(columnInfo.getColumnType());
        return columnStructureInfo;
    }
}
